package com.foo.DAO;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.foo.Entity.HistoricalData;
import com.foo.Entity.RealTimeData;

public class AnalyzedDAOImpl implements AnalyzedDAO
{
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	MapSqlParameterSource namedParameters =null;
	String query = "";
	RealTimeData[] ticker =null;
	int size=0;

	public void setDataSource(DataSource dataSource) {
		this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}

	@Override
	public RealTimeData[] selectForum(String sorttype) 
	{
		try
		{
			if(sorttype.equalsIgnoreCase("TopVolume"))
			{
				query = "select distinct * from realtimestockdata Group by ticker_symbol order by volume desc LIMIT 0,25";
			}
			else if(sorttype.equalsIgnoreCase("TopIncr"))
			{
				query = "select distinct * from realtimestockdata Group by ticker_symbol order by perc_change desc LIMIT 0,25";
			}
			else if(sorttype.equalsIgnoreCase("TopDecr"))
			{
				query = "select distinct * from realtimestockdata Group by ticker_symbol order by perc_change LIMIT 0,25";
			}

			return (RealTimeData[]) namedParameterJdbcTemplate.queryForObject(query,
					namedParameters, new RowMapper() 
			{
				public Object mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
					int j=0;
					//resultSet.setFetchSize(25);
					if (resultSet !=null)
					{
						resultSet.last();
						size=resultSet.getRow();
						ticker=new RealTimeData[size];
						resultSet.beforeFirst();
					}
					while(resultSet.next())
					{
						RealTimeData data = new RealTimeData(resultSet.getString(1),resultSet.getDouble(2),resultSet.getDouble(3),
								resultSet.getDouble(4),resultSet.getDouble(5),resultSet.getLong(6),
								resultSet.getTimestamp(7),resultSet.getDouble(8),resultSet.getInt(9));
						ticker[j]=data;
						j++;
					}
					return ticker;
				}
			});
		}
		catch(Exception e)
		{
			return null;
		}
	}
}

